/*
 * main.cpp
 *
 *  Created on: 2013-1-15
 *      Author: heqiu
 */

#include "myall.h"

ConfUnit g_ConfUnit;
SDL_Surface *g_screen = NULL;
SDL_Event g_event;
MapUnit g_MapUnit;

const int DOT_L = 10;
const int DOT_S = 2;
const float GG2 = 1.4142;

void drawPoint(uint32_t uiX, uint32_t uiY) {
	MyPoint p(uiX, uiY);
	MyPoint pw;
	g_MapUnit.getWinPoint(p, pw);
	uint32_t uiBuilding = g_MapUnit.getBuilding(uiX, uiY);
	{
		SDL_Rect wall;
		wall.x = (pw.m_x) * GG2 * (DOT_L + DOT_S) / 2;
		wall.y = (pw.m_y) / GG2 * (DOT_L + DOT_S) / 2;
		wall.w = DOT_L * GG2;
		wall.h = DOT_L / GG2;

		SDL_FillRect(g_screen, &wall,
				SDL_MapRGB(g_screen->format, 0x00, 0xff, 0xff));

		if (uiBuilding > 0) {
			if (BuildingUnit::isWay(uiBuilding)) {
				SDL_FillRect(g_screen, &wall,
						SDL_MapRGB(g_screen->format, 0xff, 0x00, 0x00));
			} else {
				SDL_FillRect(g_screen, &wall,
						SDL_MapRGB(g_screen->format, 0x00, 0x00, 0xff));
			}
		}
	}

}
void drawWindow() {
	SDL_FillRect(g_screen, &g_screen->clip_rect,
			SDL_MapRGB(g_screen->format, 0xFF, 0xFF, 0xFF));

	ScaleUnit stScaleUnit;
	int iRet = stScaleUnit.init(g_ConfUnit.getMapLong());
	if (iRet != 0) {
		myexit(__FILE__, __LINE__, iRet, "stScaleUnit.init");
	}
	iRet = g_MapUnit.init(&stScaleUnit, g_ConfUnit.getMapShort(),
			g_ConfUnit.getMapLong());
	if (iRet != 0) {
		myexit(__FILE__, __LINE__, iRet, "stMapUnit.init");
	}

	//建筑
	{
		vector<BuildingUnit> vctBuilding;
		g_ConfUnit.getBuildings(vctBuilding);
		for (uint32_t ui = 0; ui < vctBuilding.size(); ui++) {
			g_MapUnit.setBuilding(vctBuilding.at(ui));
		}
	}

	//道路
	{
		map<uint32_t, set<pair<uint32_t, uint32_t> > > mapWay;
		g_ConfUnit.getWays(mapWay);
		map<uint32_t, set<pair<uint32_t, uint32_t> > >::iterator it;
		for (it = mapWay.begin(); it != mapWay.end(); it++) {
			set<pair<uint32_t, uint32_t> > & stSet = it->second;
			set<pair<uint32_t, uint32_t> >::iterator it2;
			for (it2 = stSet.begin(); it2 != stSet.end(); it2++) {
				g_MapUnit.setWay(it2->first, it2->second, (WayType) it->first);
			}
		}
	}

	g_MapUnit.cycle(drawPoint);

	SDL_Flip(g_screen);
}
int main(int argc, char ** argv) {
	int32_t iRet = g_ConfUnit.load("./conf/root.xml");
	if (iRet != 0) {
		myexit(__FILE__, __LINE__, iRet, "g_ConfUnit.load");
	}
	printf("width=%u\n", g_ConfUnit.getWindowWidth());
	printf("height=%u\n", g_ConfUnit.getWindowHeight());
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
		myexit(__FILE__, __LINE__, -1, "SDL_Init");
	}
	g_screen = SDL_SetVideoMode(g_ConfUnit.getWindowWidth(),
			g_ConfUnit.getWindowHeight(), g_ConfUnit.getWindowBPP(),
			SDL_SWSURFACE);
	if (g_screen == NULL) {
		myexit(__FILE__, __LINE__, -1, "SDL_SetVideoMode");
	}
	SDL_WM_SetCaption(g_ConfUnit.getWindowCaption().c_str(), NULL);

	drawWindow();

	bool quit = false;
	while (quit == false) {
		while (SDL_PollEvent(&g_event)) {
			if (g_event.type == SDL_QUIT) {
				quit = true;
			}
		}
	}
	SDL_Quit();
	return 0;
}

